<template>
  <div class="order-container">
    <el-card class="order-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h1 class="title">确认订单</h1>
          <div class="header-divider"></div>
        </div>
      </template>

      <div class="order-content">
        <!-- 商品信息 -->
        <el-card class="product-card" shadow="never">
          <div class="product-info">
            <div class="product-image">
              <el-image 
                :src="product.image" 
                fit="cover" 
                style="width: 120px; height: 120px; border-radius: 8px;"
              />
            </div>
            <div class="product-details">
              <h3 class="product-title">{{ product.title }}</h3>
              <div class="product-price">
                <span class="price">¥{{ product.price }}</span>
              </div>
              <div class="product-seller">
                <el-icon><User /></el-icon>
                <span>卖家: {{ product.seller?.username || '未知' }}</span>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 收货地址 -->
        <el-card class="address-card" shadow="never">
          <div class="section-header">
            <div class="section-title">
              <el-icon><Location /></el-icon>
              <h3>收货地址</h3>
            </div>
            <el-button type="primary" link @click="showAddressDialog = true">
              <el-icon><Edit /></el-icon>
              选择地址
            </el-button>
          </div>
          
          <div v-if="selectedAddress" class="address-info">
            <div class="address-details">
              <p class="receiver">
                <span class="name">{{ selectedAddress.receiver }}</span>
                <el-tag v-if="selectedAddress.is_default" size="small" type="success" class="default-tag">默认</el-tag>
                <span class="phone">{{ selectedAddress.phone }}</span>
              </p>
              <p class="address">
                {{ selectedAddress.province }}{{ selectedAddress.city }}{{ selectedAddress.district }}{{ selectedAddress.detail }}
              </p>
            </div>
          </div>
          <div v-else class="empty-address">
            <el-button type="primary" plain @click="handleEmptyAddressClick">
              <el-icon><Plus /></el-icon>
              添加收货地址
            </el-button>
          </div>
        </el-card>

        <!-- 订单信息 -->
        <el-card class="order-info-card" shadow="never">
          <div class="section-header">
            <div class="section-title">
              <el-icon><Document /></el-icon>
              <h3>订单信息</h3>
            </div>
          </div>
          
          <div class="order-details">
            <div class="detail-item">
              <span class="label">商品金额</span>
              <span class="value">¥{{ product.price }}</span>
            </div>
            <div class="detail-item">
              <span class="label">运费</span>
              <span class="value">¥{{ shippingFee }}</span>
            </div>
            <div class="detail-item total">
              <span class="label">应付总额</span>
              <span class="value">¥{{ totalAmount }}</span>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 提交按钮 -->
      <div class="submit-area">
        <el-button 
          type="primary" 
          size="large" 
          :loading="isSubmitting"
          :disabled="!selectedAddress"
          @click="submitOrder"
          class="submit-btn"
        >
          <template #icon>
            <el-icon><Money /></el-icon>
          </template>
          提交订单 (¥{{ totalAmount }})
        </el-button>
      </div>
    </el-card>

    <!-- 地址选择对话框 -->
    <el-dialog 
      v-model="showAddressDialog" 
      title="选择收货地址" 
      width="700px"
      class="address-dialog fixed-size-dialog"
      :close-on-click-modal="false"
    >
      <div class="address-dialog-content">
        <div class="address-list-container">
          <el-scrollbar>
            <el-radio-group v-model="selectedAddressId" class="address-radio-group">
              <div 
                v-for="address in addressList" 
                :key="address.id"
                class="address-item"
                :class="{'default-address': address.is_default}"
              >
                <el-radio :label="address.id" class="list-radio">
                  <div class="address-content">
                    <div class="address-header">
                      <span class="receiver-name">{{ address.receiver }}</span>
                      <span class="receiver-phone">{{ address.phone }}</span>
                      <el-tag 
                        v-if="address.is_default" 
                        size="small" 
                        type="success"
                        class="default-tag"
                      >
                        默认地址
                      </el-tag>
                    </div>
                    <div class="address-detail">
                      <el-icon><LocationFilled /></el-icon>
                      {{ address.province }}{{ address.city }}{{ address.district }}{{ address.detail }}
                    </div>
                  </div>
                </el-radio>
              </div>
            </el-radio-group>

            <el-empty 
              v-if="addressList.length === 0" 
              description="暂无收货地址"
              class="empty-address"
              :image-size="100"
            >
              <el-button 
                type="primary" 
                @click="showAddressDialog = false"
              >
                我知道了
              </el-button>
            </el-empty>
          </el-scrollbar>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showAddressDialog = false" size="large">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmAddress" 
            :disabled="!selectedAddressId"
            size="large"
          >
            确认选择
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加地址对话框 -->
    <el-dialog 
      v-model="showAddAddressDialog" 
      title="添加收货地址" 
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form 
        :model="newAddress" 
        label-width="90px" 
        :rules="addressRules" 
        ref="addressFormRef"
      >
        <el-form-item label="收件人姓名:" prop="receiver_name">
          <el-input v-model="newAddress.receiver_name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="收件人电话:" prop="receiver_phone">
          <el-input v-model="newAddress.receiver_phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="详细地址:" prop="detail">
          <el-input v-model="newAddress.detail" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="默认地址:">
          <el-switch v-model="newAddress.is_default" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showAddAddressDialog = false">取消</el-button>
          <el-button type="primary" @click="submitNewAddress">确认添加</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Location, 
  Edit, 
  Plus, 
  Document, 
  Money, 
  User,
  LocationFilled
} from '@element-plus/icons-vue'
import apiClient from '../../utils/request'
const route = useRoute()
const router = useRouter()
const productCode = ref(route.query.product_code)

// 商品信息
const product = reactive({
  id:null,
  product_code: null,
  title: '',
  price: 0,
  original_price: 0,
  image: '',
  seller: null
})

// 地址相关
const showAddressDialog = ref(false)
const addressList = ref([])
const selectedAddressId = ref(null)
const selectedAddress = ref(null)

// 订单状态
const isSubmitting = ref(false)
const shippingFee = ref(0)
const discount = ref(0)

// 计算总金额
const totalAmount = computed(() => {
  const total = parseFloat(product.price) + parseFloat(shippingFee.value) - parseFloat(discount.value)
  return Math.max(total, 0).toFixed(2)
})




// 响应拦截器，处理 401


// 获取商品详情
const fetchProductDetails = async () => {
  try {
    const token = localStorage.getItem('access_token')
    if (!token) {
      ElMessage.error('请先登录')
      router.push('/login')
      return
    }
    if (!productCode.value) {
      ElMessage.error('缺少商品编码参数')
      router.push('/')
      return
    }
    const response = await apiClient.get(`/api/products/buyer/${productCode.value}`)
    if (response.data) {
      product.id = response.data.id
      product.product_code = response.data.product_code
      product.title = response.data.name
      product.price = response.data.price
      product.original_price = response.data.original_price || response.data.price * 1.2
      product.image = response.data.image || response.data.images?.[0]?.url || ''
      product.seller = response.data.seller
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
    ElMessage.error('获取商品详情失败，请稍后重试')
    if (error.response?.status === 401) {
      localStorage.removeItem('access_token')
      router.push('/login')
    } else if (error.response?.status === 404) {
      ElMessage.error('商品不存在')
      router.push('/')
    }
  }
}

// 获取用户地址列表
const fetchAddressList = async () => {
  try {
    const token = localStorage.getItem('access_token')
    if (!token) return
    const response = await apiClient.get('/api/users/addresses/')
    if (response.data) {
      // 自动识别分页或非分页结构
      const addresses = Array.isArray(response.data) 
        ? response.data 
        : response.data.results || []
      
      // 标准化地址数据
      const processedAddresses = addresses.map(addr => ({
        ...addr,
        province: addr.province_name || addr.province || '', 
        city: addr.city_name || addr.city || '', 
        district: addr.district_name || addr.district || '',
        receiver: addr.receiver_name || addr.receiver,
        phone: addr.receiver_phone || addr.phone,
        detail: addr.detail || addr.address_detail,
        is_default: addr.is_default || false
      }))
      
      addressList.value = processedAddresses
      
      // 自动选中默认地址
      const defaultAddress = processedAddresses.find(addr => addr.is_default)
      if (defaultAddress) {
        selectedAddressId.value = defaultAddress.id
        updateSelectedAddress(defaultAddress)
      }
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
    ElMessage.error('获取地址列表失败，请稍后重试')
  }
}

// 封装地址更新逻辑
const updateSelectedAddress = (addr) => {
  selectedAddress.value = {
    id: addr.id,
    receiver: addr.receiver,
    phone: addr.phone,
    province: addr.province,
    city: addr.city,
    district: addr.district,
    detail: addr.detail,
    is_default: addr.is_default
  }
}

// 确认选择地址
const confirmAddress = () => {
  const address = addressList.value.find(addr => addr.id === selectedAddressId.value)
  if (address) {
    updateSelectedAddress(address)
    showAddressDialog.value = false
    ElMessage.success('收货地址已更新')
  } else {
    ElMessage.warning('请选择一个收货地址')
  }
}

// 提交订单（创建订单）
const submitOrder = async () => {
  try {
    isSubmitting.value = true
    const token = localStorage.getItem('access_token')
    if (!token) {
      ElMessage.error('请先登录')
      router.push('/login')
      return
    }
    if (!selectedAddress.value) {
      ElMessage.warning('请选择收货地址')
      return
    }
    
    // 创建订单
    const orderResponse = await apiClient.post('/api/orders/', {
      product: product.id,
      address: selectedAddress.value.id,
      snapshot_price: totalAmount.value,
      status: 0
    },{headers: { 'Content-Type': 'application/json' }})
    
    if (orderResponse.data) {
      // 跳转到支付页面，携带订单信息
      router.push({
        path: '/payment',
        query: {
          order_id: orderResponse.data.id,
          order_code: orderResponse.data.order_code,
          product_title: product.title,
          snapshot_price: totalAmount.value
        }
      })
    }
  } catch (error) {
    console.error('创建订单失败:', error)
    let errorMessage = '创建订单失败，请稍后重试'
    if (error.response?.data) {
      if (typeof error.response.data === 'string') {
        errorMessage = error.response.data
      } else if (error.response.data.detail) {
        errorMessage = error.response.data.detail
      }
    }
    ElMessage.error(errorMessage)
  } finally {
    isSubmitting.value = false
  }
}

// 初始化加载
onMounted(async () => {
  if (!productCode.value) {
    router.push('/')
    return
  }
  const token = localStorage.getItem('access_token')
  if (!token) {
    ElMessageBox.confirm(
      '您尚未登录，无法下单。是否前往登录页面？',
      '提示',
      {
        confirmButtonText: '前往登录',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      router.push('/login')
    }).catch(() => {
      router.push('/')
    })
    return
  }
  await fetchProductDetails()
  await fetchAddressList()
})

// 添加新的响应式变量
const showAddAddressDialog = ref(false)
const addressFormRef = ref()
const newAddress = ref({
  receiver_name: '',
  receiver_phone: '',
  detail: '',
  is_default: false
})

// 添加表单验证规则
const addressRules = {
  receiver_name: [
    { required: true, message: '请输入收件人姓名', trigger: 'blur' },
    { max: 50, message: '长度不超过50个字符', trigger: 'blur' }
  ],
  receiver_phone: [
    { required: true, message: '请输入收件人电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ],
  detail: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { max: 200, message: '长度不超过200个字符', trigger: 'blur' }
  ]
}

// 修改空地址时的点击事件处理
const handleEmptyAddressClick = () => {
  showAddAddressDialog.value = true
}

// 添加新地址的方法
const submitNewAddress = async () => {
  try {
    await addressFormRef.value.validate()
    const response = await apiClient.post('/api/users/addresses/', newAddress.value,{headers: { 'Content-Type': 'application/json' }})
    if (response.data) {
      ElMessage.success('添加地址成功')
      showAddAddressDialog.value = false
      // 重置表单
      newAddress.value = {
        receiver_name: '',
        receiver_phone: '',
        detail: '',
        is_default: false
      }
      // 刷新地址列表
      await fetchAddressList()
      // 如果是默认地址或只有这一个地址，自动选中
      if (response.data.is_default || addressList.value.length === 1) {
        selectedAddressId.value = response.data.id
        updateSelectedAddress(response.data)
      }
    }
  } catch (error) {
    console.error('添加地址失败:', error)
    if (error.response?.data) {
      const data = error.response.data
      let msg = '添加失败'
      if (typeof data === 'object') {
        msg = Object.entries(data).map(([k, v]) => `${k}: ${Array.isArray(v) ? v.join(', ') : v}`).join('; ')
      }
      ElMessage.error(msg)
    } else {
      ElMessage.error('添加地址失败，请稍后重试')
    }
  }
}
</script>

<style scoped lang="scss">
.order-container {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  min-height: 100vh;
  padding: 40px 20px;
  background-color: #f8fafc;
}

.order-card {
  width: 100%;
  max-width: 900px;
  border-radius: 16px;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.08);
  border: none;
}
.order-card :deep(.el-card__header) {
  padding: 24px;
  border-bottom: 1px solid #f0f2f5;
}
.card-header {
  text-align: center;
}

.card-header .title {
  margin: 0;
  color: var(--el-text-color-primary);
  font-size: 24px;
  font-weight: 600;
  letter-spacing: 0.5px;
}

.card-header .header-divider {
  height: 1px;
  background: linear-gradient(90deg, transparent, var(--el-color-primary-light-5), transparent);
  margin-top: 16px;
}

.order-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.product-card,
.address-card,
.order-info-card {
  border-radius: 12px;
  border: 1px solid #f0f2f5;
}

.product-card :deep(.el-card__body),
.address-card :deep(.el-card__body),
.order-info-card :deep(.el-card__body) {
  padding: 20px;
}

.product-info {
  display: flex;
  gap: 24px;
  align-items: center;
}

.product-image {
  flex-shrink: 0;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.product-details {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.product-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  line-height: 1.4;
}

.product-price {
  display: flex;
  align-items: center;
  gap: 12px;
  
  .price {
    font-size: 22px;
    color: var(--el-color-primary);
    font-weight: 700;
  }
}

.product-seller {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
  
  .el-icon {
    font-size: 16px;
  }
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  
  .section-title {
    display: flex;
    align-items: center;
    gap: 8px;
    
    h3 {
      margin: 0;
      font-size: 18px;
      color: var(--el-text-color-primary);
      font-weight: 600;
    }
    
    .el-icon {
      color: var(--el-color-primary);
      font-size: 20px;
    }
  }
}

.address-info {
  padding: 16px;
  background-color: #f9fafc;
  border-radius: 8px;
  border: 1px solid #f0f2f5;
  
  .receiver {
    display: flex;
    align-items: center;
    gap: 12px;
    margin: 0 0 8px 0;
    font-size: 16px;
    
    .name {
      font-weight: 600;
      color: var(--el-text-color-primary);
    }
    
    .phone {
      color: var(--el-text-color-regular);
    }
    
    .default-tag {
      margin-left: auto;
      background-color: var(--el-color-primary-light-8);
      color: var(--el-color-primary);
      border-color: var(--el-color-primary-light-5);
    }
  }
  
  .address {
    margin: 0;
    font-size: 14px;
    color: var(--el-text-color-regular);
    line-height: 1.6;
  }
}

.empty-address {
  padding: 24px 0;
  text-align: center;
  border: 1px dashed #e4e7ed;
  border-radius: 8px;
  background-color: #fafbfc;
}

.order-details {
  padding: 12px 0;
  
  .detail-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 12px;
    font-size: 15px;
    color: var(--el-text-color-regular);
    
    &.total {
      margin-top: 16px;
      padding-top: 16px;
      border-top: 1px solid #f0f2f5;
      font-size: 18px;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }
  }
  
  .label {
    color: var(--el-text-color-secondary);
  }
  
  .value {
    font-weight: 500;
  }
}

.submit-area {
  margin-top: 32px;
  text-align: right;
  
  .submit-btn {
    width: 240px;
    height: 56px;
    font-size: 18px;
    font-weight: 600;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
    
    .el-icon {
      margin-right: 8px;
    }
  }
}

/* 地址选择对话框 */
:deep(.el-dialog) {
  height: 600px;
  max-height: 600px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

:deep(.el-dialog__body) {
  padding: 0;
  flex: 1;
  min-height: 0;
  overflow: hidden;
}

:deep(.el-scrollbar) {
  height: 100%;
  padding: 0 24px;
}

:deep(.el-scrollbar__view) {
  padding: 16px 0;
}

:deep(.el-radio__input) {
  margin-top: 2px;
  margin-right: 12px;
}

:deep(.el-radio__label) {
  flex: 1;
  padding: 0;
  margin: 0;
}

.address-dialog-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.address-list-container {
  flex: 1;
  padding: 0;
  overflow: hidden;
  width: 100%;
}

.address-list-container :deep(.el-scrollbar) {
  height: 100%;
  padding: 0 24px;
}

.address-list-container :deep(.el-scrollbar__view) {
  padding: 16px 0;
}

.address-radio-group {
  width: 100%;
  display: flex;
  flex-direction: column;
}

.address-item {
  width: 100%;
  padding: 16px 0;
  border-bottom: 1px solid #f0f2f5;
  box-sizing: border-box;
  transition: all 0.2s ease;
}

.address-item:last-child {
  border-bottom: none;
}

.address-item:hover {
  background-color: #f8fafc;
}

.address-item.default-address {
  background-color: rgba(103, 194, 58, 0.05);
  border-left: 3px solid var(--el-color-success);
}

.list-radio {
  width: 100%;
  margin: 0;
  display: flex;
  align-items: flex-start;

  :deep(.el-radio__input) {
    margin-top: 2px;
    margin-right: 12px;
  }

  :deep(.el-radio__label) {
    flex: 1;
    padding: 0;
    margin: 0;
  }
}

.address-content {
  width: 100%;
}

.address-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 8px;
  width: 100%;

  .receiver-name {
    font-weight: 600;
    color: var(--el-text-color-primary);
    min-width: 80px;
  }

  .receiver-phone {
    color: var(--el-text-color-secondary);
    min-width: 120px;
  }

  .default-tag {
    margin-left: auto;
    background-color: var(--el-color-primary-light-8);
    color: var(--el-color-primary);
    border-color: var(--el-color-primary-light-5);
  }
}

.address-detail {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  color: var(--el-text-color-regular);
  font-size: 14px;
  line-height: 1.5;
  width: 100%;

  .el-icon {
    color: var(--el-color-primary);
    font-size: 16px;
    margin-top: 2px;
    flex-shrink: 0;
  }
}

.empty-address {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 40px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 12px;
  padding: 16px 24px;
  border-top: 1px solid #f0f2f5;
}
</style>